package admin

import (
	"MembershipRegist/db"
	"MembershipRegist/models"
)

func (c *Controller) OrganizationAdmins() {
	var organizationAdmins []models.OrganizationAdmin

	offset := c.GetString("offset")
	limit := c.GetString("limit")
	// 不分页
	if limit == "" || limit == "0" {
		db.DB.Order("id desc").Find(&organizationAdmins)
	} else {
		db.DB.Limit(limit).Offset(offset).Order("id desc").Find(&organizationAdmins)
	}

	var total int
	db.DB.Model(&models.OrganizationAdmin{}).Count(&total)
	result := make(map[string]interface{})
	result["status"] = 200
	result["message"] = "success"
	result["total"] = total
	result["organization_admins"] = organizationAdmins
	c.Data["json"] = result
	c.ServeJSON()
}

func (c *Controller) OrganizationAdminInsert() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.ResponseFailed(201, "用户名和密码不能为空")
		return
	}

	nickname := c.GetString("nickname")
	organizationID, err := c.GetInt("organization_id")
	if err != nil {
		c.ResponseFailed(201, "organization_id 不合法")
		return
	}

	if value := db.DB.Where("id = ?", organizationID).First(&models.Organization{}); value.Error != nil {
		c.ResponseFailed(202, "organization_id 不存在")
		return
	}

	organizationAdmin := models.OrganizationAdmin{
		Username:       username,
		Password:       password,
		Nickname:       nickname,
		OrganizationID: uint(organizationID),
	}

	if value := db.DB.Create(&organizationAdmin); value.Error != nil {
		c.ResponseFailed(203, "注册失败")
		return
	}

	c.ResponseSuccess()
}

func (c *Controller) OrganizationAdminDelete() {
	adminID, err := c.GetInt("organization_admin_id")
	if err != nil {
		c.ResponseFailed(201, "organization_admin_id 不合法")
		return
	}

	if value := db.DB.Unscoped().Delete(models.OrganizationAdmin{}, "id = ?", adminID); value.Error != nil {
		c.ResponseFailed(202, "此用户不存在")
		return
	}

	c.ResponseSuccess()
}

func (c *Controller) OrganizationAdminQuery() {
	username := c.GetString("username")
	if username == "" {
		c.ResponseFailed(201, "请输入需要查询的用户名")
		return
	}

	var organizationAdmins []models.OrganizationAdmin
	db.DB.Where("username like ?", "%"+username+"%").Find(&organizationAdmins)
	result := make(map[string]interface{})
	result["status"] = 200
	result["message"] = "success"
	result["organization_admins"] = organizationAdmins
	c.Data["json"] = result
	c.ServeJSON()
}

func (c *Controller) OrganizationAdminUpdate() {
	organizationAdminID, err := c.GetInt("organization_admin_id")
	if err != nil {
		c.ResponseFailed(201, "organization_admin_id 不合法")
		return
	}

	password := c.GetString("password")
	nickname := c.GetString("nickname")

	updateValue := make(map[string]interface{})
	if password != "" {
		updateValue["password"] = password
	}
	if nickname != "" {
		updateValue["nickname"] = nickname
	}

	db.DB.Model(&models.OrganizationAdmin{}).Where("id = ?", organizationAdminID).
		Updates(updateValue)

	c.ResponseSuccess()
}
